package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String appsecret;
    @Override
    public String getOpenid(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",appsecret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String body = HttpRequest.get(url)
                .form(param)
                .execute().body();
        System.out.println(body);
        JSONObject entries = JSONUtil.parseObj(body);
//        if(entries.getInt("errcode")!=0){
//            throw new BaseException("调用微信接口失败");
//        }
        String openid = entries.getStr("openid");
        return openid;
    }
    @Override
    public String getToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String,Object> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",appsecret);
        param.put("grant_type","client_credential");
        String body = HttpRequest.get(url)
                .form(param)
                .execute().body();
        String accessToken = JSONUtil.parseObj(body).getStr("access_token");
        return accessToken;
    }
    @Override
    public String getPhone(String detailCode) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
        String accessToken = getToken();
        String body = HttpRequest.post(url + accessToken)
                .body("{\"code\": \"" + detailCode + "\"}")
                .execute().body();
        JSONObject phoneInfo = JSONUtil.parseObj(body).getJSONObject("phone_info");
        if(phoneInfo!=null){
            return phoneInfo.getStr("phoneNumber");
        }
        return null;
    }
}
